#!/usr/bin/env node

# Determine document type, name, and database name from argument list. Doc name
# is mandatory; database name is optional, and if given, objects found in the
# document file will be saved in the database, otherwise JSON text is written
# to stdout.

Usage = """
	Usage:
		xlscat -c -S sheet# fileName.xlsx | tee sheetName.csv
		| csv_json.pl sheetName | tee sheetName.json
		| node import.js http://localhost:5984/stage
"""

dbName = ''
serverName = 'localhost'
portNum = '5984'

process.argv.slice(2).forEach (v, n) ->
	switch n
		when 0 then dbName = v

if x = dbName.match /^http:\/\/(\S+?):(\d+?)\/(\S+?)$/
	serverName = x[1] if x[1]
	portNum    = x[2] if x[2]
	dbName     = x[3] if x[3]

# Define a helper to slurp in data from stdin asynchronously...
# Pass in a text variable to collect data chunks, and a function callback to
# do what you want with the collected text.
aSlurp = (cb) ->
	text = ''
	In = process.stdin
	In.resume()
	In.setEncoding 'utf8'
	In.on 'data', (data) -> text += data
	In.on 'end', -> cb text

console.log "Parsing stdin stream into documents..."
aSlurp (indocs) ->
	# Mutate JSON text into document objects
	indocs = JSON.parse indocs, 'utf8'

	# We need to transform incoming documents to outgoing documents.
	# 1. Remove documents with null 'Year'
	# 2. Remove properties with null values
	# 3. Convert property with null name to 'Note'
	console.log "Transforming document structure..."
	outdocs = []
	for doc, i in indocs when doc.Year? # 1
		for n, v of doc
			unless v? # 2
				delete doc[n]
			else if n is '' # 3
				(doc.Note = v) if v?
				delete doc[n]
		outdocs.push doc

	# Unless a database name is given on command line, the updated document objects
	# are written in JSON format to stdout.
	unless dbName
		u = require 'util'
		console.log u.inspect outdocs
		process.exit()

	# Define a callback to handle erroneous or successful document saves
	save_cb = (err, resp) ->
		if err
			console.error "#{err.error} #{err.reason}"
		else
			console.log "#{JSON.stringify resp}\n"

	# Try to connect to our database server
	cradle = require 'cradle'
	c = new cradle.Connection "http://#{serverName}", portNum,
		cache: true
		raw: false
	db = c.database dbName

	# If our database exists, save all documents, otherwise create the database
	db.exists (err, exists) ->
		if err
			console.error "#{dbName} error", err
		else if exists
			console.log "Saving documents in #{dbName}"
			db.save outdocs, save_cb
		else
			console.log "Creating #{dbName}; rerun the command to save documents in #{dbName}"
			db.create()
